package com.agile.leetcode.AESandRSAandMd5;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/6/29 15:59
 */
public class Test {
    public static void main(String[] args) throws Exception {
        String string = Base64.getEncoder().encodeToString("{\"token\":\"ISAQvrcorNyewBrf7vmRx5wGai3U_s1HyadTvxp4yUw9brgtGkHjWfcnd-SIhjZx\"}".getBytes());
        byte[] bits_token_pwds = decrypt(string.getBytes(), "bits_token_pwd");
        System.out.println(new String(bits_token_pwds));
    }
    public static byte[] decrypt(byte[] content, String password) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");// 创建AES的Key生产者
        //防止linux下 随机生成key
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG" );
        secureRandom.setSeed(password.getBytes());
        kgen.init(128, secureRandom);
        SecretKey secretKey = kgen.generateKey();// 根据用户密码，生成一个密钥
        byte[] enCodeFormat = secretKey.getEncoded();// 返回基本编码格式的密钥
        SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");// 转换为AES专用密钥
        Cipher cipher = Cipher.getInstance("AES");// 创建密码器
        cipher.init(Cipher.DECRYPT_MODE, key);// 初始化为解密模式的密码器
        byte[] result = cipher.doFinal(content);
        return result; // 明文

    }
}
